<script setup lang="ts" name="PermissionList">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Delete, Edit, Plus, View, Grid, List as ListIcon } from '@element-plus/icons-vue'
import type { Permission, PageQueryParams } from '@/model/user-role-model'
import { getPermissions, getPermissionTree, deletePermission } from '@/request/user-role-api'
import { MenuType } from '@/model/user-role-model'

// 导入组件
import PermissionForm from './components/PermissionForm.vue'
import PermissionTree from './components/PermissionTree.vue'

// 显示模式: table - 表格视图, tree - 树形视图
const viewMode = ref<'table' | 'tree'>('tree')

// 权限表格数据
const tableData = ref<Permission[]>([])
const loading = ref(false)

// 分页和搜索参数
const queryParams = reactive<PageQueryParams>({
  page: 1,
  page_size: 10,
  keyword: ''
})

// 获取权限列表
const fetchPermissionList = async () => {
  loading.value = true
  try {
    const res = await getPermissions()
    if (res.code === 0) {
      tableData.value = res.data
    } else {
      ElMessage.error(res.errorMsg || '获取权限列表失败')
    }
  } catch (error) {
    console.error('获取权限列表出错：', error)
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 树形数据
const treeData = ref<Permission[]>([])
const treeLoading = ref(false)

// 获取权限树形数据
const fetchPermissionTree = async () => {
  treeLoading.value = true
  try {
    const res = await getPermissionTree()
    if (res.code === 0 && res.data) {
      treeData.value = res.data
      console.log('获取到的权限树数据:', treeData.value)
    } else {
      ElMessage.error(res.errorMsg || '获取权限树失败')
    }
  } catch (error) {
    console.error('获取权限树出错：', error)
    ElMessage.error('获取权限树失败')
  } finally {
    treeLoading.value = false
  }
}

// 重置查询条件
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.page = 1
  fetchPermissionList()
}

// 打开权限弹窗
const dialogVisible = ref(false)
const currentPermission = ref<Permission | null>(null)
const dialogTitle = ref('创建权限')

const openDialog = (permission?: Permission) => {
  if (permission) {
    currentPermission.value = { ...permission }
    dialogTitle.value = '编辑权限'
  } else {
    currentPermission.value = null
    dialogTitle.value = '创建权限'
  }
  dialogVisible.value = true
}

// 获取树形数据
const getPermissionTreeData = async () => {
  // 获取权限树形数据
  await fetchPermissionTree()
  // 同时也获取列表数据以便表格视图使用
  await fetchPermissionList()
}

// 删除权限
const handleDelete = (permission: Permission) => {
  ElMessageBox.confirm(`确定要删除权限"${permission.name}"吗？删除后将无法恢复，且可能影响关联的角色权限设置。`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deletePermission(permission.id)
      if (res.code === 0) {
        ElMessage.success('删除成功')
        getPermissionTreeData() // 重新获取全部数据
      } else {
        ElMessage.error(res.errorMsg || '删除失败')
      }
    } catch (error) {
      console.error('删除权限出错：', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除，不做操作
  })
}

// 权限保存回调
const handlePermissionSaved = () => {
  dialogVisible.value = false
  getPermissionTreeData() // 重新获取所有数据
}

// 权限类型标签样式
const menuTypeTagType = (type: MenuType) => {
  return type === MenuType.MENU ? 'success' : 'info'
}

// 权限类型文字
const menuTypeText = (type: MenuType) => {
  return type === MenuType.MENU ? '菜单项' : '按钮/操作'
}

// 格式化层级文本
const levelText = (level: number) => {
  switch (level) {
    case 1:
      return '一级菜单'
    case 2:
      return '二级菜单'
    default:
      return `${level}级菜单`
  }
}

// 搜索过滤
const filterTableData = computed(() => {
  if (!queryParams.keyword) return tableData.value
  
  const keyword = queryParams.keyword.toLowerCase()
  return tableData.value.filter(permission => 
    permission.name.toLowerCase().includes(keyword) || 
    (permission.url?.toLowerCase().includes(keyword))
  )
})

onMounted(() => {
  // 加载权限数据，包括树形结构和列表数据
  getPermissionTreeData()
})
</script>

<template>
  <div class="permission-list-container p-4">
    <el-card class="box-card">
      <template #header>
        <div class="card-header flex items-center justify-between">
          <h2 class="text-xl font-bold">权限管理</h2>
          <div>
            <el-button-group class="mr-4">
              <el-button 
                :type="viewMode === 'tree' ? 'primary' : 'default'" 
                :icon="Grid" 
                @click="viewMode = 'tree'"
              >树形视图</el-button>
              <el-button 
                :type="viewMode === 'table' ? 'primary' : 'default'" 
                :icon="ListIcon" 
                @click="viewMode = 'table'"
              >列表视图</el-button>
            </el-button-group>
            <el-button type="primary" :icon="Plus" @click="openDialog()">新增权限</el-button>
          </div>
        </div>
      </template>
    
      <!-- 搜索区域 -->
      <div class="search-container mb-4 flex flex-wrap items-center gap-4">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入权限名称/URL"
          clearable
          class="w-80"
          @keyup.enter="fetchPermissionList"
          @clear="fetchPermissionList"
        />
        <el-button type="primary" :icon="Search" @click="fetchPermissionList">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
      
      <!-- 树形视图 -->
      <div v-if="viewMode === 'tree'" class="tree-view-container">
        <el-card class="tree-card" shadow="never" v-loading="treeLoading">
          <div class="tree-container border rounded p-4" style="max-height: 600px; overflow-y: auto;">
            <el-tree
              v-loading="treeLoading"
              :data="treeData"
              node-key="id"
              default-expand-all
              :expand-on-click-node="false"
            >
              <template #default="{ node, data }">
                <div class="custom-tree-node flex items-center justify-between w-full">
                  <div class="node-info flex items-center">
                    <span v-if="data.icon" class="mr-1">
                      <el-icon><component :is="data.icon" /></el-icon>
                    </span>
                    <span class="label">
                      {{ data.name }}
                      <span v-if="data.url" class="text-gray-500 text-xs ml-2">({{ data.url }})</span>
                      <span v-if="data.method" class="text-blue-500 text-xs ml-1">{{ data.method }}</span>
                    </span>
                  </div>
                  <div class="node-actions">
                    <el-button 
                      type="primary" 
                      link 
                      :icon="Edit"
                      @click.stop="openDialog(data)"
                    >
                      编辑
                    </el-button>
                    <el-button 
                      type="danger" 
                      link 
                      :icon="Delete"
                      @click.stop="handleDelete(data)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
        </el-card>
      </div>
      
      <!-- 列表视图 -->
      <el-table
        v-else
        v-loading="loading"
        :data="filterTableData"
        stripe
        border
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="权限名称" width="150" show-overflow-tooltip />
        <el-table-column prop="url" label="URL" min-width="180" show-overflow-tooltip />
        <el-table-column prop="method" label="方法" width="100" show-overflow-tooltip />
        <el-table-column prop="parent_id" label="父ID" width="80" />
        <el-table-column label="级别" width="100">
          <template #default="{ row }">
            {{ levelText(row.level) }}
          </template>
        </el-table-column>
        <el-table-column prop="order" label="排序" width="80" />
        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="menuTypeTagType(row.is_menu)">{{ menuTypeText(row.is_menu) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="icon" label="图标" width="100" />
        <el-table-column prop="created_at" label="创建时间" width="180" show-overflow-tooltip />
        <el-table-column label="操作" fixed="right" width="150">
          <template #default="{ row }">
            <el-button type="primary" link :icon="Edit" @click="openDialog(row)">编辑</el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 权限表单弹窗 -->
    <PermissionForm
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      :permission="currentPermission"
      @saved="handlePermissionSaved"
    />
    
  </div>
</template>

<style scoped lang="scss">
.permission-list-container {
  .el-button.el-button--primary.is-link,
  .el-button.el-button--danger.is-link {
    padding: 0 6px;
    margin-right: 0;
  }
  
  // 树形视图相关样式
  .tree-view-container {
    .tree-card {
      margin-bottom: 16px;
    }
    
    .custom-tree-node {
      width: 100%;
    }

    .node-info {
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .node-actions {
      visibility: hidden;
      transition: visibility 0s, opacity 0.3s ease;
      opacity: 0;
    }
    
    .el-tree-node:hover .node-actions {
      visibility: visible;
      opacity: 1;
    }
    
    /* 当按钮被hover时，确保其可见性 */
    .node-actions:hover {
      visibility: visible !important;
      opacity: 1 !important;
    }
    
    /* 当节点内的按钮被hover时，保持节点的hover状态 */
    .custom-tree-node:hover .node-actions {
      visibility: visible;
      opacity: 1;
    }
    
    :deep(.el-tree-node__content) {
      height: auto !important;
      min-height: 26px;
      padding: 5px 0;
    }
  }
}
</style>
